$(document).ready(function () {

  // ----------------- 全局数据--------------------

  // -----------------生命周期（立即执行函数） -----------------
  (function created() {
    renderRoleSelect();
    bindEventListener();
  })()


  function renderRoleSelect() {
    const selectIds = ["#role"]
    selectIds.forEach(selectId => {
      listRole().then(response => {
        if (response.code === 200) {
          let roles = response.data

          $("<option></option>")
            .attr("name", "roleId")
            .attr("value", "")
            .text("Select Role")
            .prop("hidden", true)
            .prop("selected", false)
            .appendTo(selectId);

          $.each(roles, function (index, role) {
            $("<option></option>")
              .attr("name", "roleId")
              .attr("value", role.id)
              .text(role.name)
              .appendTo(selectId);
          });
        }
      });
    })

  }


  function bindEventListener() {
    const $registerForm = $('#register-form');
    const $message = $('#message');
    const $submitButton = $registerForm.find('button[type="submit"]');


    $registerForm.on('submit', function (e) {
      e.preventDefault();

      // 获取表单数据
      const firstname = $('#firstname').val();
      const roleId = $('#role').val();
      const lastname = $('#lastname').val();
      const age = $('#age').val();
      const username = $('#username').val();
      const password = $('#password').val();
      const confirmPassword = $('#confirmPassword').val();

      // 清除之前的消息
      $message.addClass('d-none');

      // 验证输入
      if (!roleId||!firstname || !lastname || !age || !password || !confirmPassword) {
        showMessage('Please input all required fields!');
        return;
      }

      // 验证用户名格式
      if (!/^[a-zA-Z0-9_]{4,16}$/.test(username)) {
        showMessage('The username should consist of 4-16 letters, numbers, or underscores!');
        return;
      }

      // 验证邮箱格式
      // if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      //   showError('请输入有效的邮箱地址');
      //   return;
      // }

      // 验证密码强度
      if (password.length < 6) {
        showMessage('Password length must be at least 6 characters!');
        return;
      }

      // if (!/\d/.test(password) || !/[a-zA-Z]/.test(password)) {
      //   showError('The password should contain letters and numbers!');
      //   return;
      // }

      // 验证两次密码是否一致
      if (password !== confirmPassword) {
        showMessage('Entered passwords differ!');
        return;
      }

      // 准备发送的数据
      const registerData = {
        roleId,
        firstname,
        lastname,
        age,
        username,
        password
      };

      // 显示加载状态
      const originalButtonText = $submitButton.html();
      $submitButton.prop('disabled', true);
      $submitButton.html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Registering...');

      // 发送注册请求
      axios.post('http://localhost:8080/api/user/register', registerData, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(response => {
          if (response.data.code === 200) {
            // 显示成功消息
            $message.text('Registered successfully. After 3 seconds, you will be redirected to the login page...').removeClass('d-none alert-danger').addClass('alert-success');

            // 重置表单
            $registerForm.trigger('reset');

            // 恢复按钮状态
            $submitButton.prop('disabled', false);
            $submitButton.html(originalButtonText);

            // 3秒后跳转到登录页面
            setTimeout(() => {
              window.location.href = 'login.html';
            }, 3000);
          } else if (response.data.code === 400) {
            $submitButton.prop('disabled', false);
            $submitButton.html(originalButtonText);
            showMessage(response.data.message);
          }


        });
    });
  }


  function showMessage(message) {
    const $message = $('#message');
    $message.text(message).removeClass('d-none alert-success').addClass('alert-danger');
    // 滚动到错误消息位置
    $('html, body').animate({
      scrollTop: $message.offset().top - 100
    }, 500);
  }
});